package com.example.socket.socket.bio.server;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CharServer {
    private int DEFAULT_PORT=8886;

    private final String QUIT="quit";

    private ServerSocket serverSocket;

    private ExecutorService executorService;

    private Map<Integer, Writer> connecteClients;

    private static  String A;

    public CharServer(){
        executorService= Executors.newFixedThreadPool(10);
        connecteClients =new HashMap<>();
    }
    //客户上线
    public synchronized void addClient(Socket socket) throws IOException {
        if(socket!=null){
            int port = socket.getPort();
            BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            connecteClients.put(port,writer);
            System.out.println("客户端{"+port+"}已链接到了服务器");
        }
    }
    //客户上线
    public synchronized void removeClient(Socket socket) throws IOException {
        if(socket!=null){
            int port = socket.getPort();
            if(connecteClients.containsKey(port)){
                connecteClients.get(port).close();
                connecteClients.remove(port);
            }
        }
    }

    public boolean readyToQuit(String msg){
        return QUIT.equals(msg);
    }
    //群发消息
    public synchronized void forwardMessage(Socket socket,String fwdMsg) throws IOException {
        for (Integer id:connecteClients.keySet()){
            if(!id.equals(socket.getPort())){
                Writer writer = connecteClients.get(id);
                writer.write(fwdMsg);
                writer.flush();
            }
        }
    }

    public void start(){
        try {
            serverSocket=new ServerSocket(DEFAULT_PORT);
            System.out.println("启动服务，监听端口:"+DEFAULT_PORT);
            while (true){
                //等待客户端链接
                Socket socket = serverSocket.accept();
                //创建CharHandler线程
//                new Thread(new ChatHandler(this,socket)).start();
                executorService.execute(new ChatHandler(this,socket));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            close();
        }
    }

    public void close(){
        if(serverSocket!=null){
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        CharServer charServer=new CharServer();
        charServer.start();
    }
}
